package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 新增菜品
     * 同时插入菜品对应的口味数据，需要操作两张表：dish、dish_flavor
     * @param dishDto
     */
    @Override
    @Transactional //事务控制
    public void saveWithFlavor(DishDto dishDto) {

        //1、保存菜品的基本信息到菜品表dish
        this.save(dishDto);

        //2、得到菜品的id和菜品的口味
        Long dishId = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();

//        flavors = flavors.stream().map((item) -> {
//            item.setDishId(dishId);
//            return item;
//        }).collect(Collectors.toList());

        //3、为每个口味数据设置对应的菜品id
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }

        //4、保存菜品口味数据到菜品口味表dish_flavor
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //1、查询菜品的基本信息
        Dish dish = this.getById(id);

        //2、新建DTO，并拷贝菜品信息
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish, dishDto);

        //3、查询当前菜品对应的所有口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);

        //4、把口味信息设置到DTO
        dishDto.setFlavors(flavors);

        return dishDto;
    }

    /**
     * 更新菜品信息
     * 同时更新对应的口味信息
     * @param dishDto
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        //1、更新菜品的基本信息
        this.updateById(dishDto);

        //2、清理当前菜品对应口味数据————dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //3、添加当前提交过来的口味数据，并为每条数据设置菜品的id————dish_flavor表的insert操作
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());

        //4、批量保存口味数据到数据库
        dishFlavorService.saveBatch(flavors);
    }

    /**
     * 根据ids批量或者单个删除菜品
     * 需求分析：
     * 需要删除菜品和对应的口味信息；
     * 如果套餐存在需要删除的菜品，并且该套菜在售卖状态，不能删除；
     * 如果菜品在售卖状态，不能删除。
     * @param ids
     */
    @Override
    @Transactional
    public void deleteByIds(List<Long> ids) {
        //1。根据ids查到菜品信息
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(ids != null, Dish::getId, ids);
        List<Dish> dishList = this.list(queryWrapper);

        //2。根据ids查到包含要删除菜品对应的套餐菜品关系信息
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getDishId, ids);
        List<SetmealDish> setmealDishList = setmealDishService.list(queryWrapper1);

        //3。查看菜品有没有对应的套餐，有的话进行进一步的判断
        if (setmealDishList.size() != 0){
            //3.1。从套餐菜品关系中拿出套餐的id并放到一个集合中
            List<Long> setmealIdList = new ArrayList<>();
            for (SetmealDish setmealDish : setmealDishList) {
                setmealIdList.add(setmealDish.getSetmealId());
            }

            //3.2。根据套餐的id查出对应的套餐信息
            LambdaQueryWrapper<Setmeal> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.in(Setmeal::getId, setmealIdList);
            List<Setmeal> setmealList = setmealService.list(queryWrapper2);

            //3.3。判断对应的套餐是否是售卖状态
            for (Setmeal setmeal : setmealList) {
                if (setmeal.getStatus() == 1){
                    throw new CustomException("要删除的菜品关联的套餐还在售卖状态，不能删除！");
                }
            }
        }

        //4。查看菜品是否在售卖状态，售卖状态不能删除，否则可以删除
        for (Dish dish : dishList) {
            if (dish.getStatus() == 0){
                this.removeById(dish.getId());//删除菜品
            }else {
                throw new CustomException("有菜品还在售卖状态，无法删除！");
            }
        }

        //5。删除菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper3 = new LambdaQueryWrapper<>();
        queryWrapper3.in(ids != null, DishFlavor::getDishId, ids);
        dishFlavorService.remove(queryWrapper3);
    }

}
